/**
 * 文档工具函数
 * 用于获取思源笔记中当前文档的各种信息
 */

import { exportMdContent, sql } from '@/api'

// 检测是否为移动端
export function isMobile(): boolean {
  return window.siyuan?.ws?.url?.includes('mobile') || false
}

// 获取当前文档ID（合并两个函数）
export function getCurrentDocId(): string | null {
  const mobile = isMobile()
  
  if (mobile) {
    return document.querySelector('#editor .protyle-content .protyle-background')?.getAttribute("data-node-id") || null
  }
  
  const activeEditor = document.querySelector('.protyle.fn__flex-1:not(.fn__none)')
  return activeEditor?.querySelector('.protyle-background')?.getAttribute('data-node-id') || null
}

// 获取完整的文档信息（简化版本）
export async function getFullDocInfo() {
  console.log('=== 开始获取完整文档信息 ===')

  const docId = getCurrentDocId()
  if (!docId) {
    console.error('无法获取文档ID')
    return { id: '', title: '未获取到文档ID', error: '无法获取文档ID' }
  }

  try {
    // 并行获取文档信息
    const [apiContent, sqlInfo] = await Promise.all([
      exportMdContent(docId),
      sql(`SELECT * FROM blocks WHERE id = '${docId}'`).then(data => data?.[0] || null).catch(() => null)
    ])

    console.log('apiContent', apiContent)
    console.log('sqlInfo', sqlInfo)

    const fullInfo = {
      docId: docId,
      title: sqlInfo?.content || '未获取到标题',
      notebookId: sqlInfo?.box || '未获取到笔记本ID',
      fullContent: apiContent?.content || '',
      ...sqlInfo
    }

    console.log('完整文档信息:', fullInfo)
    console.log('=== 文档信息获取完成 ===')
    return fullInfo
  } catch (error) {
    console.error('获取文档信息时出错:', error)
    return { id: docId, title: '获取失败', error: error.message }
  }
}

// 统一的事件监听器管理
export function setupEventListeners(callbacks: {
  onDocLoaded?: (docInfo: any) => void
  onBlockIconClick?: (event: CustomEvent) => void
}) {
  const eventListeners: { [key: string]: EventListener } = {}

  if (callbacks.onDocLoaded) {
    const handleDocLoaded = (event: CustomEvent) => {
      console.log('文档加载完成事件:', event)
      setTimeout(async () => {
        const docInfo = await getFullDocInfo()
        callbacks.onDocLoaded!(docInfo)
      }, 500)
    }
    document.addEventListener('loaded-protyle-static', handleDocLoaded as EventListener)
    eventListeners['loaded-protyle-static'] = handleDocLoaded as EventListener
  }

  if (callbacks.onBlockIconClick) {
    const handleBlockIconClick = (event: CustomEvent) => {
      console.log('块菜单点击事件:', event)
      callbacks.onBlockIconClick!(event)
    }
    document.addEventListener('click-blockicon', handleBlockIconClick as EventListener)
    eventListeners['click-blockicon'] = handleBlockIconClick as EventListener
  }

  return () => {
    Object.entries(eventListeners).forEach(([eventName, listener]) => {
      document.removeEventListener(eventName, listener)
    })
  }
}

// 保持向后兼容
export function setupDocLoadListener(callback: (docInfo: any) => void) {
  return setupEventListeners({ onDocLoaded: callback })
}
